/**
 * JAVACC DEMO 1.0
 */
package com.apache.info.controller;

import com.apache.action.PlatFromAction;
import com.apache.api.manager.BaseManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultMsg;
import com.apache.api.vo.Token;
import com.apache.cache.util.Validator;
import com.apache.database.model.Page;
import com.apache.info.entity.PubMetadata;
import com.apache.info.entity.PubSortInfo;
import com.apache.info.manager.PubMetadataManager;
import com.apache.info.manager.PubSortInfoManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * description:  数据定义action
 *
 * @author Hou Dayu 创建时间：2016-8-27
 */
@Controller
@RequestMapping("info/metadata")
public class PubMetadataAction extends PlatFromAction<PubMetadata> {

    @Autowired
    private PubMetadataManager pubMetadataManager;

    @Autowired
    private PubSortInfoManager pubSortInfoManager;

    @RequestMapping("list.action")
    public ModelAndView list(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(LIST);
        view.addObject("sortId", request.getParameter("sortId"));
        return view;
    }

    @RequestMapping("metadata!data.action")
    @ResponseBody
    protected Object data(HttpServletRequest request, String page, String rows) {
        ParamsVo<PubMetadata> vo = new ParamsVo<PubMetadata>();
        PubMetadata metadata = new PubMetadata();
        if (Validator.isNotNull(request.getParameter("sortId"))) {
            metadata.setSortId(request.getParameter("sortId"));
        }
        if (Validator.isNotNull(request.getParameter("dataFullName"))) {
            metadata.setDataFullName(request.getParameter("dataFullName"));
        }
        if (Validator.isNotNull(request.getParameter("dataShortName"))) {
            metadata.setDataShortName(request.getParameter("dataShortName"));
        }
        vo.setParams("pageIndex", page);
        vo.setParams("pageSize", rows);
        vo.setObj(metadata);
        Page pageList = pubMetadataManager.getPageInfo(vo);
        Map<String, Object> mapData = new HashMap<String, Object>();
        mapData.put("total", pageList.getCount());
        mapData.put("rows", pageList.getPageObjects());
        return mapData;
    }

    @Token(save = true)
    @RequestMapping("add.action")
    protected ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(ADD);
        String mid = request.getParameter("id");
        PubMetadata metadata = new PubMetadata();
        if (Validator.isNotNull(mid)) {
            ParamsVo<PubMetadata> vo = new ParamsVo<PubMetadata>();
            vo.setInfoId(mid);
            metadata = (PubMetadata) pubMetadataManager.getInfoById(vo);
            ParamsVo<PubSortInfo> pvo = new ParamsVo<PubSortInfo>();
            pvo.setInfoId(metadata.getSortId());
            PubSortInfo sort = (PubSortInfo) pubSortInfoManager.getInfoById(pvo);
            view.addObject("sortStatus", sort.getSortStatus());
        } else {
            metadata.setSortId(request.getParameter("sortId"));
        }
        view.addObject("item", metadata);
        return view;
    }

    @Token(remove = true)
    @RequestMapping("save.action")
    @ResponseBody
    public ResultMsg save(HttpServletRequest request, HttpServletResponse response,
            @ModelAttribute PubMetadata item) {
        ResultMsg rmsg = new ResultMsg("T", "操作成功！");
        ParamsVo<PubMetadata> vo = new ParamsVo<PubMetadata>();
        if (Validator.isNull(item.getMetadataId())) {
            ////////////////////////////////////////////
            vo.setObj(item);
            String id = pubMetadataManager.saveInfo(vo);
            if (Validator.isNull(id)) {
                rmsg = getResultMsg(request, "元素信息添加失败！");
            }
        } else {
            vo.setObj(item);
            boolean mark = pubMetadataManager.editInfo(vo);
            if (!mark) {
                rmsg = getResultMsg(request, "元素信息修改失败！");
            }
        }
        return rmsg;
    }

    @RequestMapping("del.action")
    @ResponseBody
    public ResultMsg delete(HttpServletRequest request, String id) {
        ResultMsg rmsg = new ResultMsg("T", "删除成功！");
        ParamsVo<PubMetadata> vo = new ParamsVo<PubMetadata>();
        if (isNotNull(id)) {
            ParamsVo<PubSortInfo> pvo = new ParamsVo<PubSortInfo>();
            pvo.setInfoId(request.getParameter("sortId"));
            PubSortInfo sort = (PubSortInfo) pubSortInfoManager.getInfoById(pvo);
            if (Validator.isEmpty(sort)) {
                rmsg = getResultMsg(request, "请不要恶意操作！");
                return rmsg;
            } else {
                if ("1".equals(sort.getSortStatus())) {
                    rmsg = getResultMsg(request, "分类[" + sort.getSortName() + "]已发布启用不能删除元素");
                    return rmsg;
                }
            }
            vo.setInfoId(id);
            boolean mark = pubMetadataManager.deleteInfo(vo);
            if (!mark) {
                rmsg = getResultMsg(request, "元素删除失败！");
            }
        } else {
            rmsg = getResultMsg(request, "请不要恶意操作！");
        }
        return rmsg;
    }

    protected BaseManager<PubMetadata> getBaseManager() {
        return pubMetadataManager;
    }

    protected String getPrefix() {
        return "info/metadata-";
    }

    private ResultMsg getResultMsg(HttpServletRequest request, String msg) {
        request.getSession().setAttribute("formToken", request.getAttribute("formToken"));
        ResultMsg rmsg = new ResultMsg("F", msg);
        return rmsg;
    }

    public static void main(String[] args) {
        System.out.println("start!");

        String colNames = "memberEname,memberCname,memberNo,shortName,memberType,orgType,mobile,phone,email,regTime,clientManager,certType,certNo,validityPeriod,memberLevel,infoFrom,createUserEname,updateUserEname,updateTime,status,deptId,auditStatus,strFiftyOne,strFiftyTwo,strFiftyThree,strFiftyFour,strFiftyFive,strFiftySix,strFiftySeven,strFiftyEight,strFiftyNine,strFiftyTen,strFiftyEleven,strFiftyTwelve,strFiftyThirteen,strFiftyFourteen,strFiftyFifteen,strFiftySixteen,strFiftySeventeen,strFiftyEighteen,strFiftyNineteen,strFiftyTwenty,strHundredOne,strHundredTwo,strHundredThree,strHundredFour,strHundredFive,strHundredSix,strHundredSeven,strHundredEight,regCapital,legalPerson,orgCode,enterpriseType,economyNature,creditGrade,address,legalCertType,legalCertNo,legalLicence,linkName,linkMobile,linkPhone,linkEmail,linkFax,linkPostCode,linkAddress,operatorName,operatorCertType,operatorCertNo,operatorMobile,operatorPhone,operatorEmail,operatorAddress";

        String str[] = colNames.split(",");
        for (String colName : str) {

            String sqlPre = "insert into pub_metadata (METADATA_ID, SORT_ID, DATA_TYPE, DATA_FULL_NAME, DATA_LENGTH, DATA_RESTRICT, DATA_SHORT_NAME, DATA_ATTR, FOREIGN_KEY_NAME, RESERVED1, RESERVED2, RESERVED3, COLMUN_TYPE, REQ_URL, RES_COLMUN, IF_ADD, IF_EDIT, IF_LIST, IF_SEARCH) values (";
            String primarkey = Validator.generate();
            String sqlMid = "'" + primarkey + "', 'member', '5', '" + colName + "', 50, '3', '"
                    + upperCharToUnderLine(colName) + "', '" + colName
                    + "', '', '', '', '', '', '', '', 'F', 'F', 'F', 'F'";
            String sqlLast = " );";
            System.out.println(sqlPre + sqlMid + sqlLast);

        }
        System.out.println("end!");

    }

    private static String upperCharToUnderLine(String param) {
        Pattern p = Pattern.compile("[A-Z]");
        if (param == null || param.equals("")) {
            return "";
        }
        StringBuilder builder = new StringBuilder(param);
        Matcher mc = p.matcher(param);
        int i = 0;
        while (mc.find()) {
            builder.replace(mc.start() + i, mc.end() + i, "_" + mc.group().toLowerCase());
            i++;
        }
        if ('_' == builder.charAt(0)) {
            builder.deleteCharAt(0);
        }
        return builder.toString();
    }

}
